<template>
  <styledElDialog
    title="实时喊话"
    width="360px"
    :visible.sync="visible"
    :modal="false"
    highlight-title
    :left-title="leftTitle"
    size="small"
    append-to-body
    :destroy-on-close="true"
    :top="top"
    :left="left"
    class="realTimeShoutBox"
    @close="close"
  >
    <div class="shoutBox">
      <div
        class="circle"
        :class="{ active: isSpeaking }"
        @click="toggleSpeaking"
      >
        <div v-show="isSpeaking" class="animationBox">
          <i
            v-for="item in 5"
            :key="item"
            class="waveline"
            :style="{ animationDelay: (5 - item) * -0.1 + 's' }"
          />
        </div>
      </div>
      <div class="message">
        <span v-if="isSpeaking">喊话中 {{ seconds }} s</span>
        <span v-else>点击喊话</span>
      </div>
    </div>
  </styledElDialog>
</template>
<script>
import { startTalk, stopTalk } from "@/api/alarmEvent/mapHome";
import { Recorder } from "@/components/audio/recorder";
import styledElDialog from "./styledElDialog";

export default {
  name: "RealTimeShout",
  components: {
    styledElDialog,
  },
  props: {
    top: {
      type: Number,
      default: 128,
    },
    left: {
      type: Number,
      default: undefined,
    },
    leftTitle: Boolean,
    detailData: {
      type: Object,
      default: () => {
        console.log("解决sonar问题");
      },
    },
  },
  data() {
    return {
      visible: false,
      tempLinkConfType: "",
      isSpeaking: false,
      seconds: 0,
      timer: null,
      lines: [5, 10, 15, 20, 25],
      pushStreamAddress: "",
      lockId: null,
      messageId: null,
    };
  },
  methods: {
    toggleSpeaking() {
      if (this.isSpeaking) {
        this.stopSpeaking();
      } else {
        this.startSpeaking();
      }
    },
    startSpeaking() {
      // 实时喊话-开始喊话 （获取锁以及播发） !this.lockId
      if (!this.lockId) {
        const param = {
          deviceCode: this.detailData.deviceCode,
          volume: "100",
          protocolType: location.protocol === "https:" ? "2" : "5",
          networkType: "1",
          streamCodeId: "3",
          sampleRate: "44.1",
        };
        startTalk(param).then((res) => {
          if (res.code == 200) {
            // 2执行播发 获取ws推流地址socketUrl
            this.lockId = res.data.data.lockId;
            this.pushStreamAddress = res.data.data.pushStreamAddress;
            this.messageId = res.data.data.messageId;
            console.log("startTalk-----", res.data);
            console.log("pushStreamAddress-----", this.pushStreamAddress);
            // 3获取音频，推流
            this.sendStream();
            this.isSpeaking = true;
            this.timer = setInterval(() => {
              this.seconds++;
            }, 1000);
          } else {
            // 设备正在使用，请稍后再试 设备权限资源释放失败
            if (res.msg && res.msg.indexOf("资源释放") > -1) {
              this.$message.error("该喇叭设备已经有人在喊话，请稍后再试");
            } else {
              this.$message.error(res.msg);
            }
          }
        });
      } else {
        // 3获取音频，推流
        this.sendStream();
        this.isSpeaking = true;
        this.timer = setInterval(() => {
          this.seconds++;
        }, 1000);
      }
    },
    sendStream() {
      try {
        Recorder.start(this.pushStreamAddress, this.errorFunCell, 44100).catch(
          (error) => {
            console.log("error", error);
            this.stopSpeaking();
            this.$message.error(error.message);
          }
        );
      } catch (e) {
        console.log("推流失败", e);
        // 推流失败 - 关闭麦克风
        this.stopSpeaking();
        this.$message.error("推流失败:" + e);
      }
    },
    errorFunCell(errorTitle) {
      this.$message.error(errorTitle);
      this.stopSpeaking();
    },
    stopSpeaking() {
      // 关闭麦克风
      Recorder.stop();
      this.isSpeaking = false;
      clearInterval(this.timer);
      this.seconds = 0;
      // 4释放锁 this.lockId = null;
      if (this.lockId) {
        stopTalk({
          deviceCode: this.detailData.deviceCode,
          lockId: this.lockId,
          messageId: this.messageId,
        }).then((res) => {
          if (res.code == 200) {
            console.log("stopTalk-----", res);
            this.lockId = null;
            this.pushStreamAddress = null;
            this.messageId = null;
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },
    open() {
      this.visible = true;
    },
    close() {
      // 关闭麦克风
      Recorder.stop();
      // 4释放锁 this.lockId = null;
      if (this.lockId) {
        stopTalk({
          deviceCode: this.detailData.deviceCode,
          lockId: this.lockId,
          messageId: this.messageId,
        }).then((res) => {
          if (res.code == 200) {
            console.log("stopTalk-----", res);
            this.lockId = null;
            this.pushStreamAddress = null;
            this.messageId = null;
            this.visible = false;
            setTimeout(() => {
              this.closeConfigDialog();
            });
          } else {
            this.$message.error(res.msg);
            this.closeConfigDialog();
          }
        });
      } else {
        this.visible = false;
        setTimeout(() => {
          this.closeConfigDialog();
        });
      }
    },
    closeConfigDialog() {
      this.$emit("close");
    },
  },
};
</script>
<style scoped lang="scss">
.lystyle {
  .shoutBox {
    .circle {
      background: url("~@/assets/image/common/ly/shoutImg_d.png") no-repeat
        center/100% 100%;
      &.active {
        background-image: url("~@/assets/image/common/ly/shoutImg_i.png");
      }
    }
  }
}
.gtstyle {
  .shoutBox {
    .circle {
      background: url("~@/assets/image/common/gt/shout-off.svg") no-repeat
        center/100% 100%;
      &.active {
        background-image: url("~@/assets/image/common/gt/shout-on.svg");
      }
    }
  }
}
.shoutBox {
  .circle {
    position: relative;
    margin: 0 auto 17px;
    width: 106px;
    height: 106px;
    cursor: pointer;
    background: url(../../../assets/image/functionMenu/shoutImg_1.png) no-repeat
      center/100% 100%;
    &.active {
      background-image: url(../../../assets/image/functionMenu/shoutImg.png);
      //animation: pulse 1s ease-in-out infinite;
    }
  }
}
.animationBox {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  .waveline {
    width: 6px;
    height: 34px;
    background-color: white;
    // margin: 0 4px;
    border-radius: 4px;
    animation: lineAnimation 0.8s linear infinite;
  }

  .waveline + .waveline {
    margin-left: 6px;
  }
}
.message {
  font-size: 14px;
  color: #e8f3fe;
  line-height: 1;
  text-align: center;
}
.realTimeShoutBox.styledElDialog.iwhale-industrystyle {
  /deep/ {
    .el-dialog__body {
      padding: 44px 0 47px;
    }
  }
}

@keyframes lineAnimation {
  0% {
    height: 34px;
  }
  50% {
    height: 6px;
  }
  100% {
    height: 34px;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}
</style>
